//
//  SegmentView.m
//  iOSCodeLearning
//
//  Created by TFAppleWork-Summer on 2018/3/15.
//  Copyright © 2018年 Ace. All rights reserved.
//

#import "SegmentView.h"
#import "SegmentViewCollectionViewCell.h"
#import "SegmentViewConfigModel.h"

static NSString * const kSegmetnViewCellIndentifier = @"kSegmetnViewCellIndentifier";

@interface SegmentView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIView  *lineView;

/**
 所有item的宽度放在一个数组里面
 */
@property (nonatomic, strong) NSArray *itemWithArr;





@end;

@implementation SegmentView
- (instancetype)initWithFrame:(CGRect)frame itemArr:(NSArray<NSString *> *)itemArr configModel:(SegmentViewConfigModel *)configModel{
    if (self = [super initWithFrame:frame]) {
        
        self.currentIndex = 0;
        self.configModel = configModel;
        self.itemArr = itemArr;
        
        [self addSubview:self.collectionView];
        [self.collectionView addSubview:self.lineView];
        [self setLineViewFrame];
    }
    return self;
}

- (void)segmetViewUpdateToIndex:(NSInteger)index byPercent:(CGFloat)percent{
    
    if (index < 0 || index >= [self collectionView:self.collectionView numberOfItemsInSection:0])
    {
        return;
    }
    else
    {
        UICollectionViewLayoutAttributes *currentAttributes = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
        UICollectionViewLayoutAttributes *distanceAttributes = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        // 目标与当前之间的距离
        CGFloat distance = distanceAttributes.center.x - currentAttributes.center.x;
        // 实际应该偏移的量
        CGFloat offset = distance * percent;
        
        CGFloat widthOffset = distanceAttributes.size.width - currentAttributes.size.width;
        self.lineView.frame = CGRectMake(0, 0, distanceAttributes.size.width - self.configModel.itemSeace  , 4);
        
        
        
        CGPoint lineCeter = currentAttributes.center;
        lineCeter.x = lineCeter.x + offset;
        lineCeter.y = CGRectGetHeight(self.collectionView.frame) - 2;
        self.lineView.center = lineCeter;
        
       
        
        
        
        
        NSLog(@"%f   %ld",percent  ,index  );
    }
}

-(void)scrollToIndex:(NSInteger)index{
    // 1 将原先的选中状态取消
    [self collectionView:self.collectionView didDeselectItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    // 2 当前的下标赋值
    self.currentIndex = index;
    // 3 选中新的cell
    [self collectionView:self.collectionView didSelectItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    // 4 将当前选中cell滚到中间
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    
    
}


#pragma mark -UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    SegmentViewCollectionViewCell *cell = (SegmentViewCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kSegmetnViewCellIndentifier forIndexPath:indexPath];
    [cell refreshWithSegmentViewModel:self.configModel string:self.itemArr[indexPath.row]];
    if (indexPath.row == self.currentIndex)
    {
        cell.titleLabel.textColor = self.configModel.selectColor;
    }
    else{
        cell.titleLabel.textColor = self.configModel.color;
    }
    
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    // 让collectionView滚到当前的位置
    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
    
    if (_currentIndex != indexPath.row)
    {// 如果选中不是当前的，才需要进行一下操作
        // 1 当前的_currentIndex 赋值
        _currentIndex = indexPath.row;
        // 2 调用block
        if (self.didSelectBlock) {
            self.didSelectBlock(_currentIndex, @"");
        }
        // 3 滚动lineView
        [UIView animateWithDuration:0.3 animations:^{
            [self segmetViewUpdateToIndex:self.currentIndex byPercent:1.0];
        }];
    }

    [collectionView reloadData];
    
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    SegmentViewCollectionViewCell *cell = (SegmentViewCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.titleLabel.textColor = self.configModel.color;

}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake([self.itemWithArr[indexPath.row] floatValue], CGRectGetHeight(self.collectionView.frame) );
}


#pragma mark - private
-(void)caluateItemWidth{
    if (self.itemArr.count != 0)
    {
        CGFloat allItemWidth = 0.0;
        NSMutableArray *tempArr = [NSMutableArray array];
        for (NSString *item in _itemArr) {
            CGFloat width = MAX([item sizeWithAttributes:@{NSFontAttributeName:_configModel.font}].width + _configModel.itemSeace, _configModel.itemMinWidth );
            [tempArr addObject: @(width)];
            allItemWidth += width;
        }
        self.itemWithArr = [NSArray arrayWithArray:tempArr];
        
        // 在item 过少的时候，用边距让collectionView居中
        CGFloat sectionInset = 0.0;
        CGFloat viewWidth = CGRectGetWidth(self.frame);
        if (allItemWidth < viewWidth) {
            sectionInset = (viewWidth - allItemWidth)/2.0;
        }
        UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
        layout.sectionInset = UIEdgeInsetsMake(0, sectionInset, 0, sectionInset);
    }
}

- (void)setLineViewFrame{
    UICollectionViewLayoutAttributes *currentAttribute = [self.collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentIndex inSection:0]];
    NSString *item = self.itemArr[self.currentIndex];
    CGFloat lineViewWidth = [item sizeWithAttributes:@{NSFontAttributeName:_configModel.font}].width;
    
    self.lineView.frame = CGRectMake(0,0 ,lineViewWidth, 4);
    CGPoint lineViewCenter = CGPointMake(currentAttribute.center.x, CGRectGetHeight(self.collectionView.frame) -2);
    self.lineView.center = lineViewCenter;
}


#pragma mark - lazy - load

- (void)setItemArr:(NSArray<NSString *> *)itemArr{
    _itemArr = itemArr;
    // 计算每个item的宽度
    [self caluateItemWidth];
}

-(UICollectionView*)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = 0.0;
        layout.minimumInteritemSpacing = 0.0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[SegmentViewCollectionViewCell class] forCellWithReuseIdentifier:kSegmetnViewCellIndentifier];
    }
    return _collectionView;
}

-(UIView*)lineView{
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = [UIColor blueColor];
    }
    return _lineView;
}


@end
